<template>
  <div class="p-3">
    <a-form>
      <a-form-item class="!mb-3">
        <a-button type="primary" @click="showCreateModal">新增</a-button>
      </a-form-item>
    </a-form>
    <a-table
      :bordered="true"
      :columns="columns"
      row-key="id"
      :data-source="tableData"
      :pagination="pagination"
      :loading="tableLoading"
      :scroll="{ x: true }"
      class="break-all"
    >
      <template #bodyCell="{ column, record }">
        <div v-if="column.key === 'oper'">
          <a-button class="mr-1 mb-1" type="primary" @click="toggleLine(record)">
            {{ record.status ? t("common.doOffline") : t("common.doOnline") }}
          </a-button>
          <a-button class="mr-1 mb-1" type="primary" @click="showUpdateModal(record)">{{ t("common.edit") }}</a-button>
          <a-button danger type="primary" @click="deleteRecord(record)">{{ t("common.delete") }}</a-button>
        </div>
        <a-image v-else-if="column.key === 'pictureList'" :src="record.pictureList" :width="200" />
        <div v-else-if="column.key === 'id'" class="w-24">{{ record.id }}</div>
      </template>
    </a-table>
    <a-modal
      v-model:visible="modalVisible"
      :title="modalTitle"
      @ok="modalOk"
      width="100%"
      wrap-class-name="full-modal"
      :body-style="{ overflow: 'auto' }"
    >
      <a-form class="article-form">
        <a-form-item label="文章标题" v-bind="validateInfos.name">
          <a-input v-model:value="modelRef.name" />
        </a-form-item>
        <a-form-item label="文章作者" v-bind="validateInfos.author">
          <a-input v-model:value="modelRef.author" />
        </a-form-item>
        <a-form-item label="列表图片" v-bind="validateInfos.pictureList">
          <CommonUpload v-model:fileUrl="modelRef.pictureList" />
        </a-form-item>
        <a-form-item label="查看权限" v-bind="validateInfos.viewPermissions">
          <a-select v-model:value="modelRef.viewPermissions" :options="memberLevelsData" />
          <a-spin v-if="loadingMember" />
          <a-empty v-if="!loadingMember && memberLevelsData.length === 0" />
        </a-form-item>
        <a-form-item label="首页标签" v-bind="validateInfos.labelIds">
          <a-checkbox-group v-model:value="modelRef.labelIds" :options="labelData" />
          <a-spin v-if="loadingLabel" />
          <a-empty v-if="!loadingLabel && labelData.length === 0" />
        </a-form-item>
        <a-form-item label="首页专栏" v-bind="validateInfos.specialColumnIds">
          <a-checkbox-group v-model:value="modelRef.specialColumnIds" :options="specialColumnData" />
          <a-spin v-if="loadingColumn" />
          <a-empty v-if="!loadingColumn && specialColumnData.length === 0" />
        </a-form-item>
        <a-form-item label="文章内容" v-bind="validateInfos.content" class="editor-form-item">
          <div v-if="loadingEditor" class="text-center bg-gray-50 rounded-md py-20">
            <a-spin />
          </div>
          <Editor v-model="modelRef.content" :api-key="tinyMCEApiKey" :init="editorInit" @init="onEditorInit" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>
<script lang="ts" setup>
import { onMounted, reactive, ref } from "vue";
import { useI18n } from "/@/locales/useI18n";
import { Api, Article, getAllSpecialColumns, getAllLabels, Label, SpecialColumn } from "/@/api/manage/officialContent";
import { uploadFile, UploadFileResult } from "/@/api/common";
import { useCURD } from "/@/hooks/web/useCURD";
import Editor from "@tinymce/tinymce-vue";
import { getTinyMCELangInfo } from "/@/utils/tinymce";
import CommonUpload from "/@/components/CommonUpload.vue";
import env from "/@/base/env";
import { getAllMemberLevels, MemberLevel } from "/@/api/manage/setting";
import { toggleLineByStatus, getStatusColumn, getOperColumn } from "/@/components/business";
import { ID } from "/@/api/models";

const { t } = useI18n();
const columns = [
  {
    title: "文章ID",
    dataIndex: "id",
    key: "id",
  },
  {
    title: "文章名称",
    dataIndex: "name",
  },
  {
    title: "作者姓名",
    dataIndex: "author",
  },
  {
    title: "列表图片",
    dataIndex: "pictureList",
    key: "pictureList",
  },
  getStatusColumn(),
  {
    title: "标签",
    dataIndex: "labelIds",
  },
  {
    title: "查看权限",
    dataIndex: "viewPermissions",
  },
  getOperColumn(),
];
const modelRef = reactive<Article>({
  author: "",
  content: "",
  labelIds: [],
  memberVisibleContent: "",
  name: "",
  pictureList: "",
  specialColumnIds: [],
  status: 0,
  theTop: 0,
  viewPermissions: "",
});
const {
  modalVisible,
  modalTitle,
  validateInfos,
  showCreateModal,
  showUpdateModal,
  modalOk,
  deleteRecord,
  pagination,
  tableLoading,
  tableData,
  reloadTable,
  curd,
} = useCURD<Article, any>({
  isPagination: true,
  createTitle: "新增文章",
  updateTitle: "编辑文章",
  deleteMessage: "确认删除该文章吗？",
  modelRef,
  fieldRules: ["name", "author", "content", "labelIds", "specialColumnIds", "viewPermissions", "pictureList"],
  cudUrl: Api.articles,
  getPageUrl: Api.articles,
  onBeforeOk(model, isCreate) {
    model.specialColumnIds = (model.specialColumnIds as ID[]).join(",");
    model.labelIds = (model.labelIds as ID[]).join(",");
    if (isCreate) {
      model.status = 0;
    }
  },
  async onBeforeShowModal(data) {
    if (data) {
      data.labelIds = (data.labelIds as string).split(",");
      data.specialColumnIds = (data.specialColumnIds as string).split(",");
    }
    if (loadingLabel.value) {
      const allLabels = (await getAllLabels()) as Label[];
      loadingLabel.value = false;
      labelData.value = allLabels.map((item) => ({
        label: item.labelName,
        value: item.id,
      }));
      const allSpecialColumns = (await getAllSpecialColumns()) as SpecialColumn[];
      loadingColumn.value = false;
      specialColumnData.value = allSpecialColumns.map((item) => ({
        label: item.specialColumnName,
        value: item.id,
      }));
      const allMembers = (await getAllMemberLevels()) as MemberLevel[];
      loadingMember.value = false;
      memberLevelsData.value = allMembers.map((item) => ({
        label: item.levelName,
        value: item.id,
      }));
    }
  },
});
onMounted(async () => {
  await reloadTable();
});
function toggleLine(record) {
  toggleLineByStatus({
    record,
    curd,
    reloadTable,
    tableLoading,
  });
}
//tinymce
const tinyMCEApiKey = env.tinyMCEApiKey;
const editorInit = {
  height: 800,
  menubar: true,
  plugins: "image,lists,advlist,fullscreen,code,preview,print",
  toolbar1:
    "undo redo | bold italic underline strikethrough | fontselect fontsizeselect formatselect | alignleft aligncenter alignright alignjustify | outdent indent |  numlist bullist checklist | fullscreen",
  toolbar2: "forecolor backcolor removeformat | preview print | image | code",
  images_upload_handler: async function (blobInfo, success, failure) {
    const file = blobInfo.blob(); //转化为易于理解的file对象
    const re = (await uploadFile({
      file,
    })) as UploadFileResult;
    if (re) {
      success(re.url);
    } else {
      console.log("upload fail", re);
      failure("上传失败，请稍候再试");
    }
  },
};
const langInfo = getTinyMCELangInfo();
if (langInfo) {
  Object.assign(editorInit, langInfo);
}
const loadingEditor = ref(true);
function onEditorInit() {
  loadingEditor.value = false;
}
//modal
const labelData = ref<any>([]);
const specialColumnData = ref<any>([]);
const memberLevelsData = ref<any>();
const loadingLabel = ref(true);
const loadingColumn = ref(true);
const loadingMember = ref(true);
</script>
<style lang="less">
.full-modal {
  .ant-modal {
    max-width: 100%;
    top: 0;
    padding-bottom: 0;
    margin: 0;
  }
  .ant-modal-content {
    display: flex;
    flex-direction: column;
    height: calc(100vh);
  }
  .ant-modal-body {
    flex: 1;
  }
}
.article-form {
  .ant-form-item-label {
    width: 85px;
    text-align: right;
  }
}
.editor-form-item {
  .ant-form-item-control-input-content > textarea {
    display: none;
  }
}
</style>
